package com.user.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.ResultCode;
import com.common.RocketMqConstant;
import com.common.Util.ObjectUtil;
import com.common.Util.StringUtils;
import com.user.config.Exception.ServiceException;
import com.user.config.Exception.ServiceExceptionUtil;
import com.user.config.SMSConf;
import com.user.controller.vo.loginVo;
import com.user.controller.vo.userVo;
import com.user.dao.SysUserDao;
import com.user.dao.SysUserRoleDao;
import com.user.entity.SysUser;
import com.user.entity.SysUserRole;
import com.user.rocketmq.RocketMqTemplate;
import com.common.Message.vo.SMSMessage;
import com.user.service.IUser;
import com.user.util.RequestUtil;
import com.user.util.impl.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @program: Member_Perks_Store
 * @description:
 * @author: 无恙
 * @create: 2024-06-17 13:59
 **/

@Service
public class IUserImpl extends ServiceImpl<SysUserDao, SysUser> implements IUser {



    private RedisUtil redisUtil;

    private RocketMqTemplate rocketMqTemplate;

    @Resource
    private SysUserRoleDao userRoleDao;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }


    @Autowired
    @Qualifier("rocketMQ")
    public void setRocketMqTemplate(RocketMqTemplate rocketMqTemplate) {
        this.rocketMqTemplate = rocketMqTemplate;
    }

    @Override
    public void sendCode(String phone) {
        if(StringUtils.isBlank(phone)) return;
        //生成随机验证码
        String code = StringUtils.RandomNumber(SMSConf.CODE_LENGTH);
        //保存验证码
        redisUtil.set(phone, code, SMSConf.CODE_EXPIRE_TIME);
        //消息队列发送验证码
        SMSMessage smsMessage = new SMSMessage(phone, code);
        rocketMqTemplate.send(RocketMqConstant.SMS_TOPIC, RocketMqConstant.SMS_TAG, smsMessage);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean register(userVo userVo) {
        //判断验证码
        String redisCode = (String) redisUtil.get(userVo.getPhone());
        if(StringUtils.isBlank(redisCode)){
            throw new ServiceException(2619,"验证码已过期，请重新获取");
        }
        if(!userVo.getCode().equals(redisCode)){
            throw new ServiceException(2620,"验证码错误！");
        }
        final SysUser covert ;
        try {
            //加密密码
            userVo.setPassword(StringUtils.MD5(userVo.getPassword()));
            covert = ObjectUtil.covert(userVo, SysUser.class);
        } catch (InstantiationException |IllegalAccessException e) {
            throw ServiceExceptionUtil.exception(ResultCode.STUDENT_NUMBER_EXISTS);
        }
        try {
            covert.setCreateTime(new Date());
            save(covert);
            //获取用户ID
            Long userId = getOne(new QueryWrapper<SysUser>().eq("phone",userVo.getPhone())).getId();
            //添加用户角色
            userRoleDao.insert(SysUserRole.builder().userId(userId).roleId(3L).build());
        } catch (Exception e) {
            // 异常处理，可以进行日志记录等操作
            throw new ServiceException(2621,"用户注册失败");
        }
        return true;
    }

    @Override
    public SysUser login(loginVo loginUser) {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        String s = StringUtils.MD5(loginUser.getPassword());
        wrapper.eq(SysUser::getPhone,loginUser.getPhone());
        wrapper.last("limit 1");
        wrapper.select(SysUser::getId, SysUser::getUsername, SysUser::getPassword, SysUser::getIsDelete);
        SysUser user = this.getOne(wrapper,false);
        if(!user.getPassword().equals(s)){
            throw ServiceExceptionUtil.exception(ResultCode.LOGIN_PASSWORD_ERROR);
        }
        if(cn.hutool.core.util.ObjectUtil.isNotNull(user)){
            SysUser u = new SysUser();
            u.setId(user.getId());
            u.setLastLoginTime(new Date());
            u.setLastLoginIp(RequestUtil.getIp());
            this.updateById(u);
        }
        return user;
    }

    @Override
    public boolean improvePermission(long user_id, long role_id) {
        try {
            // 检查数据有效性，isValidRole方法用于验证角色ID的有效性
            if (!isValidRole(role_id)) {

                return false;
            }
            // 根据用户ID查询用户角色信息
            SysUserRole sysUserRole = userRoleDao.selectById(user_id);
            if (sysUserRole == null) {
                // 如果查询不到用户角色信息,返回

                return false;
            }

            // 更新用户角色ID
            sysUserRole.setRoleId(role_id);

            // 更新用户角色信息
            userRoleDao.updateById(sysUserRole);

            return true;
        } catch (Exception e) {
            // 对于任何异常，可以考虑记录日志并返回更新失败
            return false;
        }
    }
    private boolean isValidRole(long role_id) {
        // role_id从1,2,3代表超管，管理员，小二，检查roleId是否大于0
        return role_id > 1 && role_id < 3;
    }


}
